package me.zhengjie.modules.mnprogram.rest;

import io.swagger.annotations.*;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.modules.mnprogram.bo.NewCoderBO;
import me.zhengjie.modules.mnprogram.domain.NewCoderDTO;
import me.zhengjie.modules.mnprogram.domain.UserCollectDTO;
import me.zhengjie.modules.mnprogram.domain.WxUser;
import me.zhengjie.modules.mnprogram.repository.*;
import me.zhengjie.modules.mnprogram.service.NewCoderService;
import me.zhengjie.modules.mnprogram.soup.Result;
import me.zhengjie.modules.mnprogram.vo.NewCoderVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

@Api(value = "面经接口", tags = "面经列表和详情相关接口")
@CrossOrigin
@RestController
@RequestMapping("/api")
public class NewCoderController {

    private static SimpleDateFormat sf = null;

    @Autowired
    private NewCoderService newCoderService;
    @Autowired
    NewCoderRepository newCoderRepository;
    @Autowired
    WxUserRepository wxUserRepository;
    @Autowired
    UserCollectRepository userCollectRepository;
    @Autowired
    ImgRepository imgRepository;

    @RequestMapping(value = "/newcoder",method = RequestMethod.GET)
    @ApiOperation(value = "面经列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量"),
            @ApiImplicitParam(name = "type", value = "面经类型，Java,iOS等"),
            @ApiImplicitParam(name = "openid", value = "openid,userid传一个即可")

    })
    @AnonymousAccess
    public Page getAll(@RequestParam(name = "pageNo",required = false) Integer pageNo,
                       @RequestParam(name = "pageSize",required = false) Integer pageSize,
                       @RequestParam(name = "type",required = false)String type,
                       @RequestParam(name = "openid",required = false)String openid,
                       @RequestParam(name = "keyword",required = false)String keyword
                                    ){


        if (pageNo == null){
            pageNo = 1;
        }
        if (pageSize==null){
            pageSize =10;
        }
        if (StringUtils.isNotBlank(keyword)){
            return null;
        }else {
            Sort sort = Sort.by(Sort.Direction.DESC,"createTime"); // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
            Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort); // （当前页， 每页记录数， 排序方式）
            NewCoderDTO dto = new NewCoderDTO();
            dto.setType(type);
            Example<NewCoderDTO> example= Example.of(dto);
            Page<NewCoderDTO> list = newCoderRepository.findAll(example,pageable);
            List<NewCoderVO> newCoderVOList = new ArrayList<>();
            list.getContent().stream().forEach(x->{
                NewCoderVO newCoderVO = new NewCoderVO();
                BeanUtils.copyProperties(x,newCoderVO);
                x.setContent(null);
                newCoderVOList.add(newCoderVO);
            });
            WxUser user = wxUserRepository.findUserByOpenid(openid);
            for (NewCoderVO x : newCoderVOList) {
                if (user!=null){
                    UserCollectDTO userCollect = userCollectRepository.findByUserIdAndAndInterviewId(user.getId(),x.getId());
                    if (userCollect!=null){
                        x.setIsCollect(true);
                    }else {
                        x.setIsCollect(false);
                    }
                }else {
                    x.setIsCollect(false);
                }
                Date d = new Date(Long.valueOf(x.getCreateTime()));
                sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                x.setCreateTime(sf.format(d));
                Random random = new Random();
                x.setImage_url(imgRepository.getOne(random.nextInt(150)+1).getImgUrl().trim());
            }
            return  new PageImpl<>(newCoderVOList, pageable, list.getTotalElements());
        }
    }





    @ApiOperation(value = "修改面经详情保存")
    @PutMapping(value = "/newcoder/save")
    @AnonymousAccess
    public Result<NewCoderDTO> putNewCoder(@ApiParam("面经对象") @RequestBody NewCoderBO newCoderBO){
//        List<NewCoderDTO> list = newCoderRepository.findAll();
//        Long id = list.stream().mapToLong(NewCoderDTO::getId).max().getAsLong();
//        newCoderRepository.findById(id+1);
//        dto.setId(Long.valueOf(id));
        if(newCoderBO.getId() ==null){
            return new Result(500,"id不能为空",null);
        }
        NewCoderDTO newCoderDTO = newCoderService.updateNewCoder(newCoderBO);
        return new Result(200,"保存成功",newCoderDTO);
    }
    @ApiOperation(value = "新增面经详情保存")
    @PostMapping(value = "/newcoder/save")
    @AnonymousAccess
    public Result<NewCoderDTO> getNewCoder(@ApiParam("面经对象") @RequestBody NewCoderBO newCoderBO){
        //TODO 必填空判

        NewCoderDTO newCoderDTO = newCoderService.insertNewCoder(newCoderBO);
        return new Result(200,"保存成功",newCoderDTO);
    }



    @ApiOperation(value = "面经删除")
    @PostMapping(value = "/newcoder/delete")
    @AnonymousAccess
    public Result<NewCoderDTO> getNewCoder(@ApiParam("面经id") @RequestParam("id")Long id){
        newCoderRepository.deleteById(id);
        return new Result(200,"保存成功",null);
    }



    @ApiOperation(value = "面经详情")
    @ApiImplicitParam(name = "id", value = "面经id")
    @RequestMapping(value = "/newcoderdetail",method = RequestMethod.GET)
    @AnonymousAccess
    public NewCoderVO getNewCoder(@RequestParam(name ="id") Long id,
                                  @RequestParam(name = "openid",required =false) String openid){
        NewCoderDTO  dto = newCoderRepository.findById(id).get();
        dto.setViewNum(dto.getViewNum()+1);
        newCoderRepository.save(dto);
        NewCoderVO vo = new NewCoderVO();
        BeanUtils.copyProperties(dto,vo);
//        Date d = new Date(Long.valueOf(dto.getCreateTime()));
//        sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        vo.setCreateTime(sf.format(d));
        WxUser user = wxUserRepository.findUserByOpenid(openid);
        if(user!=null) {
            UserCollectDTO userCollectDTO =   userCollectRepository.findByUserIdAndAndInterviewId(user.getId(), id);
            if (userCollectDTO!=null){
                vo.setIsCollect(true);
            }else {
                vo.setIsCollect(false);
            }

        }else{
            vo.setIsCollect(false);
        }
        Random random = new Random();
        vo.setImage_url(imgRepository.getOne(random.nextInt(150)+1).getImgUrl().trim());

        return vo;
    }
    @ApiOperation(value = "面经收藏")
    @ApiImplicitParam(name = "id", value = "面经id")
    @RequestMapping(value = "/collect",method = RequestMethod.GET)
    @AnonymousAccess
    public UserCollectDTO collect(@RequestParam(name = "id") Long id,
                                  @RequestParam(name = "openid",required = false) String openid
    ){

        WxUser user = wxUserRepository.findUserByOpenid(openid);
        UserCollectDTO userCollect= userCollectRepository.findByUserIdAndAndInterviewId(user.getId(),id);
        if (userCollect!=null){
            userCollectRepository.delete(userCollect);
            return  null;
        }else {
            userCollect = new UserCollectDTO();
            userCollect.setId(UUID.randomUUID().toString());
            userCollect.setInterviewId(id);
            userCollect.setUserId(user.getId());
            userCollect.setCreateTime(new Date());
            userCollectRepository.save(userCollect);
            return userCollect;
        }
    }


    @ApiOperation(value = "我的收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量"),
            @ApiImplicitParam(name = "openid", value = "openid,userid传一个即可")

    })
    @RequestMapping(value = "/myCollect",method = RequestMethod.GET)
    @AnonymousAccess
    public Page<NewCoderVO> myCollect(@RequestParam(name = "pageNo",required = false) Integer pageNo,
                                      @RequestParam(name = "pageSize",required = false) Integer pageSize,
                                      @RequestParam(name = "openid",required = false) String openid
    ){

        WxUser user = wxUserRepository.findUserByOpenid(openid);
        if (user!=null){
            Sort sort = Sort.by(Sort.Direction.DESC,"createTime"); // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
            Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort); // （当前页， 每页记录数， 排序方式）
            UserCollectDTO dto = new UserCollectDTO();
            dto.setUserId(user.getId());
            Example<UserCollectDTO> example= Example.of(dto);
            Page<UserCollectDTO> userCollects= userCollectRepository.findAll(example,pageable);
            List<NewCoderVO> newCoderVOList = new ArrayList<>();
            userCollects.getContent().stream().forEach(x->{
                NewCoderVO newCoderVO = new NewCoderVO();
                NewCoderDTO  newCoder = newCoderRepository.getOne(x.getInterviewId());
                BeanUtils.copyProperties(newCoder,newCoderVO);
                newCoderVO.setIsCollect(true);
                Random random = new Random();
                newCoderVO.setImage_url(imgRepository.getOne(random.nextInt(150)+1).getImgUrl().trim());

                newCoderVOList.add(newCoderVO);

            });
            return  new PageImpl<>(newCoderVOList, pageable, userCollects.getTotalElements());

        }
        return  null;
    }


}
